<template>
  <div :class="className" :style="{height:height,width:width}"/>
</template>

<script>
import echarts from 'echarts'
import resize from './mixins/resize'

require('echarts/theme/macarons') // echarts theme

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    async initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.chart.setOption(this.chartData)
    },

    // 格式化日期
    formatDate(date) {
      date = new Date(date)
      let myyear = date.getFullYear()
      let mymonth = date.getMonth() + 1
      let myweekday = date.getDate()
      mymonth < 10 ? mymonth = '0' + mymonth : mymonth
      myweekday < 10 ? myweekday = '0' + myweekday : myweekday
      return `${myyear}-${mymonth}-${myweekday}`
    },

    // 获取当前月的天数
    mGetDate() {
      var date = new Date()
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      var day = date.getDate()
      var d = new Date(year, month, day)
      return d.getDate()
    },

    //返回当前月日期
    getCurrentMonth() {
      // 获取当前月的所有日期
      let now = new Date()
      let current_month_num = this.mGetDate()
      let current_month = []
      for (let i = 1; i <= current_month_num; i++) {
        let day = now.setDate(i)
        let everyDay = this.formatDate(day)
        current_month.push(everyDay)
      }
      return current_month
    }
  }
}
</script>
